package com.tanhua.dubbo.api;

import com.tanhua.manage.domain.mongo.RecommendUser;
import com.tanhua.manage.domain.mongo.Visitor;
import com.tanhua.manage.domain.vo.PageResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class VisitorApiImpl implements VisitorApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 谁看过我
     * @param userId
     * @param lastQueryTime
     * @return
     */
    @Override
    public List<Visitor> queryLast4Visitors(Long userId, Long lastQueryTime) {

        //1. 构建条件
        Query query = new Query(Criteria.where("userId").is(userId));
        // 是否需要时间条件
        if(null != lastQueryTime){
            // 有时间条件
            query.addCriteria(Criteria.where("date").gte(lastQueryTime));
        }
        //2. 按时间降序
        query.with(Sort.by(Sort.Order.desc("date")));
        //3. 取前4条, 查1页(1-1) skip省略，取4条
        query.limit(4);
        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);

        //查询登录用户与访客的缘分值
        if (!CollectionUtils.isEmpty(visitors)){
            // 取出所有访客的id
            List<Long> visitorUserIds = visitors.stream().map(Visitor::getVisitorUserId).collect(Collectors.toList());
            // 构建批量查询条件
            Query scoreQuery = new Query(Criteria.where("userId").in(visitorUserIds).and("toUserId").is(userId));
            List<RecommendUser> recommendUsers = mongoTemplate.find(scoreQuery, RecommendUser.class);
            Map<Long, Double> scoreMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(recommendUsers)) {
                scoreMap = recommendUsers.stream().collect(Collectors.toMap(RecommendUser::getUserId, RecommendUser::getScore));
            }

            final Map<Long,Double> scoreMap1 = scoreMap;
            visitors.forEach(visitor -> {
                Double score = scoreMap1.get(visitor.getScore());
                if (null == score){
                    score = RandomUtils.nextDouble(60,80);
                }
                visitor.setScore(score);
            });
        }
        return visitors;
    }

    /**
     * 保存访客记录
     */
    @Override
    public void save(Visitor visitor) {
        visitor.setDate(System.currentTimeMillis());
        mongoTemplate.save(visitor);
    }

    /**
     * 分页查询用户最近的访客
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPageByUserId(Long userId, Long page, Long pageSize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        Long total = mongoTemplate.count(query,Visitor.class);
        List<RecommendUser> userList = new ArrayList<>();
        if (total>0){
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
            List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);
            List<Long> visitorIds = visitors.stream().map(Visitor::getVisitorUserId).collect(Collectors.toList());
            Query infoQuery = new Query(Criteria.where("toUserId").is(userId).and("userId").in(visitorIds));
            userList = mongoTemplate.find(infoQuery, RecommendUser.class);
        }
        return PageResult.pageResult(page,pageSize,userList,total);
    }
}

